<template>
  <div class="records" v-loading="loading">
  <!-- 暂时隐藏 -->
    <!-- <div class="records-head" v-if="false">
      <div class="head-left">
        <div class="head-title">按预约状态筛选</div>
        <div class="check-g">
          <el-checkbox-group v-model="checkStatus">
            <el-checkbox label="1">包含取消</el-checkbox>
            <el-checkbox label="2">包含失约</el-checkbox>
            <el-checkbox label="3">包含待定</el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      <div class="head-right">
        <div class="head-title">按预约类型筛选</div>
        <div class="check-g">
          <el-checkbox-group v-model="checkType">
            <el-checkbox label="1">包含预约</el-checkbox>
            <el-checkbox label="2">包含到店</el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
    </div> -->
    <div class="records-content">
      <div class="record-item" v-for="(i, index) in recordList" :key="i.showDay + index">
        <zdateIcon :dataDate="{showYear: i.showYear, showDay: i.showDay}"></zdateIcon>
        <zrecords 
          :rowData='i'
          :recordData="i"
          @handleEditItem="handleEditItem"
          @handleClickLog="handleClickLog"
          @handleClickCancel="handleClickCancel"
        ></zrecords>
      </div>

      <!-- 空数据展示 -->
      <el-empty v-if="recordList.length <= 0" description="暂无数据"></el-empty>
    </div>
  </div>

  <!-- 操作日志 -->
    <zdialog title="操作日志" :width="'45%'" @handleClose="closeOperation" v-model="openOperation">
      <template #body>
        <div class="operaation-log">
          <el-table
            :data="operationData"
            style="width: 100%">
            <el-table-column prop="createTime" label="操作时间" width="180" show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="userName" label="操作人" >
            </el-table-column>
            <el-table-column prop="updateType" label="操作类型" >
            </el-table-column>
            <el-table-column prop="details" label="变更记录" width="240">
              <template #default="scope">
              <div v-for="i in scope.row.details">
                <span style="background: orange; color: white;">{{i.columnShowName}}</span> 
                <span >{{i.beforeValue || '无'}}</span> ->
                <span >{{i.afterValue}}</span>
              </div>
                
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
    </zdialog>

  <!-- 修改记录 -->
  <zdialog title="修改记录" @handleClose="closeDialog" v-model="logDialogVisible" :btnData="logDialogBtnData">
      <template #body>
        <div class="flex-wrap">
          <component :is="showWidget(item.type)" v-for="item in editLogData" :key="item.name" :struc="item" :passWidth="33.33"  />
        </div>
      </template>
  </zdialog>
  <!-- / 预约/  -->
  <el-drawer
			size="45%"
			:title="title"
			v-model="showDrawer"
			:before-close="drawerClose" destroy-on-close>
			

			<!-- <zregister v-if="isADD === 'register'"
				@cancel="cancel" 
				@handlebtn="handlebtn"
        @reloadList="reloadList"
        @clickRegisterStatus="clickRegisterStatus"
        :registerInfo="registerInfo"
        :userId="userId"
				></zregister> -->

			<zmakeanapp v-if="isADD === 'makeanapp'"
				@handlebtn="handlebtn"
				@cancel="cancel"
        @reloadList="reloadList"
        :makeanappInfo="makeanappInfo"

				></zmakeanapp>
	</el-drawer>
</template>

<script lang="ts">
import zrecords from "../../../components/styleBorder/records.vue";
import zdateIcon from "../../../components/styleBorder/dateIcon.vue";
import { defineComponent, reactive, toRefs, ref, watch, onMounted, onUnmounted } from "vue";
import zdialog from '@components/dialog/dialog.vue'
import useShowWidget from "../../../components/widget/usechoose";
import useDataCheck, { DataStruc } from "./../../../hook/datastruc";

import zmakeanapp from "../../../components/patient/makeAnAppointment.vue"
import zregister from "../../../components/patient/register.vue"

import { cancelSubscribeApi } from "../../../api/reservation"

import useRequet, { RespData } from "../../../hook/network"
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router';

type DateTime = {
  showYear: string,
  showDay: string
}
export default defineComponent({
    name: 'Record',
    components:{
      zrecords,
      zdateIcon,
      zdialog,

      zmakeanapp,
      zregister,
    },
    setup() {
      const route = useRoute()
      const dataCheck = useDataCheck();
      const showWidget = useShowWidget;
      const request = useRequet({ path: "" });
      const list = reactive({
        checkStatus: ['1', '2', '3'],
        checkType: ['1', '2'],
        loading: false,
      })
      let id = route.params.id
      watch(() => route.params.id, (newID, prevID) => {
        id = newID
        if(newID) {
          getRecord()
        }
        
      })
      const date: DateTime = {
        showYear: '',
        showDay: ''
      }
      type RecordList = {
        id: number,
        masterUserName: string,
        showTime: string,
        detailType: string,
        subCompanyName: string,
        showYear: string,
        showDay: string,
        status: string,
        secondaryUserName: string,
        subscribeLog: any
      }
      const recordList = ref([] as RecordList[])
      const getRecord = () => {
        list.loading = true
        request.sendRequest({
          address: 'sick/record/getCustomerRecordDetailList',
          params: {
            customerId: id
          },
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
            console.log(resp.data)
            recordList.value = resp.data

            list.loading = false
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg)
            
          },
          method: "POST",
        })
      }
      getRecord()

      // 取消预约
      const handleClickCancel = (id: number) => {
        ElMessageBox.confirm('此操作将取消改患者预约, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          cancelLog(id)
        }).catch(() => {
            ElMessage({
              type: 'info',
              message: '已取消',
            });
        })
      }

      const cancelLog = async(id:number) => {
        let res:any = await cancelSubscribeApi({}, id);
        if(res.code !== 0) return ElMessage.error(res.msg)
        ElMessage.success('取消预约成功')
        // 取消成功刷新列表
        getRecord()
      }


      const closeDialog = () => {
        logDialogVisible.value = false
      }
      const logID = ref()
      const logDialogVisible = ref(false)

      // 修改数据
      const editLogData = ref([
        {
          id: 529,
            name: "detailType",
            viewName: "就诊类型",
            type: 102,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        },
        {
          id: 529,
            name: "medicalSourcesType",
            viewName: "就诊来源类型",
            type: 102,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        },
        {
          id: 529,
            name: "medicalSources",
            viewName: "就诊来源",
            type: 102,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        },
        {
          id: 529,
            name: "masterUserId",
            viewName: "医生",
            type: 202,
            groupId: 501,
            dataSource: "/company/user/user/getDoctorList",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        },
        {
          id: 529,
            name: "secondaryUserId",
            viewName: "咨询师",
            type: 202,
            groupId: 501,
            dataSource: "/company/user/user/getConsultList",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 1,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        }
      ])

      const handleEditItem = async(rowData: any) => {
        console.log('修改', rowData)
        logID.value = rowData.id
        let {id} = rowData
        await getMakeanapp(id)

        showDrawer.value = true
        title.value = "修改预约"
        isADD.value = 'makeanapp'
        // logDialogVisible.value = true
        // editLogData.value.forEach(i => {
          
        //   for(let o in rowData) {
        //     if(i.name === o) {
        //       i.value = rowData[o]
        //     }
        //   }
        // })
      }

    const makeanappInfo = ref({} as any)
    // 获取预约信息
    const getMakeanapp = (id: number) => {
      makeanappInfo.value = {}
      return new Promise((resolve, reject) => {
          request.sendRequest({
          address: `sick/record/getSubLogByDetailId/${id}`,
          params: {},
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error('获取预约信息' + resp.msg)
            makeanappInfo.value = resp.data
            resolve('')
          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error('获取预约信息' + resp.msg)
            reject()
          },
          method: "GET",
        })
      })
    }

          // 刷新列表
    const reloadList = () => {
      getRecord()
    }

    // 抽屉 --》 新建预约部分
    const showDrawer = ref(false)
    const title = ref('')
    const isADD = ref('')
    

    const saveAndRegister = () => {
			isADD.value = 'register'
			title.value = "挂号"
		}

    const handlebtn = () => {
      isADD.value = 'add'
			title.value = "个人信息"
    }
    const drawerClose = () => {
      ElMessageBox.confirm('此操作将关闭窗口, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
				showDrawer.value = false
			}).catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
      })
    }
    const cancel = () => {
      showDrawer.value = false
    }

      type LogType = {
        id: number,
        detailType: string,
        medicalSourcesType: string,
        medicalSources: string,
        masterUserId: number,
        secondaryUserId: number
      }
      const logDialogBtnData = [
        {
          name: '关闭',
          func: (data:object) => {
            console.debug('关闭',JSON.parse(JSON.stringify(data)))
            closeDialog()
          }
        },
        {
          name: '保存',
          func: (data:object) => {
            console.debug('保存',JSON.parse(JSON.stringify(data)))
            if(!dataCheck.checkAll()) {
              ElMessage.warning('有未填')
              return false
            }
            
            let params = {} as LogType
            params.id = logID.value
            editLogData.value.forEach(i => {
              params[i.name] = i.value
            })

            request.sendRequest({
              address: 'sick/record/updateRecordDetail',
              params,
              success: (resp: RespData) => {
                if(resp.code !== 0) return ElMessage.error('修改记录' + resp.msg)
                ElMessage.success('修改记录成功')
                closeDialog()
                getRecord()
              },
              fail: (resp: RespData) => {
                if(resp.code !== 0) return ElMessage.error('修改记录' + resp.msg)
              },
              method: "POST",
            })
          }
        }
      ]

      const operationData = ref([])
      const openOperation = ref(false)
      const closeOperation = () => {
        openOperation.value = false
      }

      const getlogList = (id: number) => {
        request.sendRequest({
          address: `sick/record/getDetailUpdateLogById/${id}`,
          params: {},
          success: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
            console.log(resp.data)
            operationData.value = resp.data

          },
          fail: (resp: RespData) => {
            if(resp.code !== 0) return ElMessage.error(resp.msg)
            
          },
          method: "GET",
        })
      }

      const handleClickLog = (id: number) => {
        getlogList(id)
        openOperation.value = true
      }
      
      onUnmounted(() => {
        dataCheck.clearDataCheck();
      });
      return {
        ...toRefs(list),
        request,
        recordList,
        getRecord,
        handleEditItem,

        handleClickCancel,

        showWidget,

        closeDialog,
        logDialogVisible,
        editLogData,
        logDialogBtnData,

        openOperation,
        operationData,
        handleClickLog,
        closeOperation,

        showDrawer,
        title,
        isADD,
        saveAndRegister,
        reloadList,
        handlebtn,
        drawerClose,
        cancel,
        makeanappInfo,
      }
    }
})
</script>

<style lang="scss" scoped>
.records {
  height: 100%;
  overflow: hidden;
  .records-head {
    border-bottom: 1px solid $mainColor;
    height: 40px;
    line-height: 40px;
    background: $a2-Color;
    font-size: 12px;
    display: flex;
    .head-left {
      display: flex;
    }
    .head-right {
      display: flex;
    }
    .head-title {
        padding-right: 10px;
        padding-left: 20px;
    }
    .check-g {
      padding: 0 10px;
      font-size: 12px;
      color: #000;
    }
  }
  .records-content {
    // display: flex;
    padding: 20px;
    box-sizing: border-box;
    height: 100%;
    overflow: scroll;
    
    .record-item {
      width: 100%;
      display: flex;
      margin-bottom: 15px;
    }
  }
}


</style>